package com.example.justauth;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.request.AuthGiteeRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
public class HelloController {

    @RequestMapping("/render")
    public void renderAuth(HttpServletResponse response) throws IOException {
        AuthRequest authRequest = getAuthRequest();
        response.sendRedirect(authRequest.authorize(AuthStateUtils.createState()));
    }
    @RequestMapping("/callback")
    @ResponseBody
    public String login(AuthCallback callback) {
        AuthRequest authRequest = getAuthRequest();
        return JSON.toJSONString(authRequest.login(callback));
    }

    private AuthRequest getAuthRequest() {
        return new AuthGiteeRequest(AuthConfig.builder()
                .clientId("02ff188d7db6246ef5d3ab3dbd036e242cf2b4c58d787f70f3dccba7b3b32444")
                .clientSecret("cf01e6db9fff777fb420074612f1b1278ee9a0ed58a2424b08074aac20d94d03")
                .redirectUri("http://localhost:8081/callback")
                .build());
    }


}
